package com.siyuanren.gcocp.web.wx;

import com.siyuanren.gcocp.common.config.PublicConfig;
import com.siyuanren.gcocp.consts.GcocpConsts;
import com.siyuanren.gcocp.consts.RedisConsts;
import com.siyuanren.gcocp.entity.WxUser;
import com.siyuanren.gcocp.exception.WxException;
import com.siyuanren.gcocp.facade.JedisFacade;
import com.siyuanren.gcocp.service.WxUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author guwr
 */
@Slf4j
public class BaseWxController {

    @Autowired
    protected WxUserService userService;
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected JedisFacade jedisFacade;

    /**
     * 获取当前用户ID
     */
    protected Integer getUserId() {
        if (PublicConfig.IS_DEV_STATUS) {
            return 86;
        }
        String tokenVal = getTokenVal();
        if (StringUtils.isBlank(tokenVal)) {
            log.info("token is null");
            throw WxException.NOT_LOGIN_ERROR;
        }
        tokenVal = String.format(RedisConsts.TOKEN_PREFIX, tokenVal);
        String userId = jedisFacade.get(tokenVal);
        return Integer.parseInt(userId);
    }

    /**
     * 获取当前用户ID
     */
    protected WxUser getWxUser() {
        WxUser user = userService.getById(getUserId());
        return user;
    }

    /**
     * 获取cookie值
     */
    private String getTokenVal() {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            log.warn("cookies is null");
            throw WxException.NOT_LOGIN_ERROR;
        }
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if (Objects.equals(name, RedisConsts.TOKEN)) {
                return cookie.getValue();
            }
        }
        return StringUtils.EMPTY;
    }
}
